package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
	flag       int
}

// NewClient 创建客户端
func NewClient(serverIp string, serverPort int) *Client {
	//创建客户端对象
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: serverPort,
		flag:       999,
	}
	//链接server
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	if err != nil {
		fmt.Println("net.Dial error:", err)
		return nil
	}
	client.conn = conn
	//返回客户端
	return client
}

// menu 客户端菜单
func (client *Client) menu() bool {
	var b int
	fmt.Println("1.公聊模式")
	fmt.Println("2.私聊模式")
	fmt.Println("3.更新用户名")
	fmt.Println("0.退出")
	_, err := fmt.Scanln(&b)
	if err != nil {
		return false
	}
	if b >= 0 && b <= 3 {
		client.flag = b
		return true
	} else {
		fmt.Println("请输入合法的选项")
		return false
	}
}

// DealResponse 处理server回应的消息
func (client *Client) DealResponse() {
	_, err := io.Copy(os.Stdout, client.conn)
	if err != nil {
		fmt.Println("deal response error:", err)
		return
	}
}

// Run 客户端开始工作
func (client *Client) Run() {
	for client.flag != 0 {
		for client.menu() != true {
		}
		switch client.flag {
		case 1:
			//公聊模式
			client.PublicChat()
			break
		case 2:
			//私聊模式
			client.PrivateChat()
			break
		case 3:
			//更新用户名
			client.UpdateName()
			break
		}
	}
}

// SelectUsers 选择聊天对象
func (client *Client) SelectUsers() {
	sendMsg := "who\r\n"
	_, err := client.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("client.conn.Write error:", err)
		return
	}
}

// PrivateChat 私聊模式
func (client *Client) PrivateChat() {
	var remoteName string
	var chatMsg string
	client.SelectUsers()
	fmt.Println("请输入聊天对象的名字，exit退出")
	_, err := fmt.Scanln(&remoteName)
	if err != nil {
		fmt.Println("scan error: ", err)
	}
	for remoteName != "exit" {
		fmt.Println("请输入聊天内容，exit退出")
		_, err := fmt.Scanln(&chatMsg)
		if err != nil {
			fmt.Println("scan error: ", err)
			return
		}
		for chatMsg != "exit" {
			//发送给服务器
			if len(chatMsg) != 0 {
				sendMsg := "to|" + remoteName + "|" + chatMsg + "\r\n"
				_, err := client.conn.Write([]byte(sendMsg))
				if err != nil {
					fmt.Println("client.conn.Write error:", err)
					break
				}
			}

			chatMsg = ""
			fmt.Println("请输入聊天内容，exit退出")
			_, err := fmt.Scanln(&chatMsg)
			if err != nil {
				fmt.Println("scan error: ", err)
				break
			}
		}
		client.SelectUsers()
		fmt.Println("请输入聊天对象的名字，exit退出")
		_, err = fmt.Scanln(&remoteName)
		if err != nil {
			fmt.Println("scan error: ", err)
			return
		}
	}
}

// PublicChat 公聊模式
func (client *Client) PublicChat() {
	//提示用户输入信息
	var chatMsg string
	fmt.Println("请输入聊天内容，exit退出")
	_, err := fmt.Scanln(&chatMsg)
	if err != nil {
		fmt.Println("scan error: ", err)
		return
	}
	for chatMsg != "exit" {
		//发送给服务器
		// 消息不为空
		sendMsg := chatMsg + "\r\n"
		if len(chatMsg) != 0 {
			_, err := client.conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("client.conn.Write error:", err)
				break
			}
		}

		chatMsg = ""
		fmt.Println("请输入聊天内容，exit退出")
		_, err := fmt.Scanln(&chatMsg)
		if err != nil {
			fmt.Println("scan error: ", err)
			return
		}
	}
}

// UpdateName 更新用户名
func (client *Client) UpdateName() bool {
	fmt.Println("请输入用户名")
	_, err := fmt.Scanln(&client.Name)
	if err != nil {
		fmt.Println("error: ", err)
		return false
	}
	sendMsg := "rename|" + client.Name + "\r\n"
	_, err = client.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("error: ", err)
		return false
	}
	return true
}

var serverIp string
var serverPort int

// init 初始化方法 读取命令行参数
func init() {
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "设置服务器IP地址（默认127.0.0.1）")
	flag.IntVar(&serverPort, "port", 8889, "设置服务器端口号（默认8889）")
}

func main() {
	// 命令解析
	flag.Parse()
	client := NewClient(serverIp, serverPort)
	if client == nil {
		fmt.Println("connection failed")
		return
	}
	fmt.Println("connection success")
	//启动goroutine去处理server的回执消息
	go client.DealResponse()
	//启动客户端业务
	client.Run()
}
